import {
	Alert,
	Button,
	Checkbox,
	Col,
	Form,
	Input,
	Row,
	Tabs,
	message,
	Space,
	Card,
	Divider,
} from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
	UserOutlined,
	LockOutlined,
	MobileOutlined,
	SafetyCertificateOutlined,
} from "@ant-design/icons";
import { useHandleToken } from "@/store/userStore";
import {
	LoginStateEnum,
	useLoginStateContext,
} from "./providers/LoginStateProvider";
import {
	getSmsCode,
	loginByPassword,
	loginBySms,
} from "@/api/services/loginService";
import { Navigate, Link } from "react-router-dom";
import ForgotPasswordForm from "./ForgotPasswordForm";

function LoginForm() {
	const { t } = useTranslation();
	const [loading, setLoading] = useState(false);
	const [activeTab, setActiveTab] = useState("password");
	const [smsLoading, setSmsLoading] = useState(false);
	const [countdown, setCountdown] = useState(0);
	const [form] = Form.useForm();
	const { loginState, setLoginState } = useLoginStateContext();
	const [loginType, setLoginType] = useState<
		"password" | "register" | "forgot-password"
	>("password");

	const handleToken = useHandleToken();

	if (loginState !== LoginStateEnum.LOGIN) return null;

	const handleFinish = async ({ username, password, mobile, code }: any) => {
		setLoading(true);
		try {
			let res;
			if (activeTab === "password") {
				res = await loginByPassword({ mobile: username, password });
			} else {
				res = await loginBySms({ mobile, code });
			}

			// 登录成功后更新token并跳转
			await handleToken(res.token, res.user);
		} catch (error) {
			// 登录失败时不重置表单
			return false;
		} finally {
			setLoading(false);
		}
	};

	const handleSendCode = async (form: any) => {
		try {
			const mobile = form.getFieldValue("mobile");
			if (!mobile) {
				message.error("请输入手机号");
				return;
			}
			if (!/^1\d{10}$/.test(mobile)) {
				message.error("手机号格式不正确");
				return;
			}

			setSmsLoading(true);
			await getSmsCode(mobile);
			message.success("验证码发送成功");

			// 开始倒计时
			setCountdown(60);
			const timer = setInterval(() => {
				setCountdown((prev) => {
					if (prev <= 1) {
						clearInterval(timer);
						return 0;
					}
					return prev - 1;
				});
			}, 1000);
		} catch (error: any) {
			message.error(error.message || "验证码发送失败");
		} finally {
			setSmsLoading(false);
		}
	};

	const PasswordLoginForm = () => {
		return (
			<Card>
				<Form
					name="password-login"
					size="large"
					form={form}
					initialValues={{
						remember: true,
						username: "",
						password: "",
					}}
					onFinish={handleFinish}
					autoComplete="off"
					preserve={true}
					className="space-y-6"
				>
					<Form.Item
						name="username"
						rules={[
							{ required: true, message: t("sys.login.accountPlaceholder") },
							{ min: 3, message: "用户名至少3个字符" },
						]}
					>
						<Input
							prefix={<UserOutlined className="text-gray-400" />}
							placeholder={t("sys.login.userName")}
							className="rounded-lg"
						/>
					</Form.Item>
					<Form.Item
						name="password"
						rules={[
							{ required: true, message: t("sys.login.passwordPlaceholder") },
							{ min: 6, message: "密码至少6个字符" },
						]}
					>
						<Input.Password
							prefix={<LockOutlined className="text-gray-400" />}
							placeholder={t("sys.login.password")}
							className="rounded-lg"
						/>
					</Form.Item>
					<Form.Item>
						<div className="flex items-center justify-between">
							<Form.Item name="remember" valuePropName="checked" noStyle>
								<Checkbox>{t("sys.login.rememberMe")}</Checkbox>
							</Form.Item>

							<Link
								className="text-sm text-primary hover:text-primary-dark"
								onClick={() => setLoginType("forgot-password")}
							>
								忘记密码
							</Link>
						</div>
					</Form.Item>

					<Form.Item>
						<Button
							type="primary"
							htmlType="submit"
							className="w-full rounded-lg"
							loading={loading}
						>
							{t("sys.login.loginButton")}
						</Button>
					</Form.Item>
				</Form>
			</Card>
		);
	};

	const MobileLoginForm = () => {
		return (
			<Card>
				<Form
					name="mobile-login"
					size="large"
					onFinish={handleFinish}
					form={form}
					autoComplete="off"
					preserve={true}
					className="space-y-6"
				>
					<Form.Item
						name="mobile"
						rules={[
							{ required: true, message: "请输入手机号" },
							{ pattern: /^1\d{10}$/, message: "手机号格式不正确" },
						]}
					>
						<Input
							prefix={<MobileOutlined className="text-gray-400" />}
							placeholder="请输入手机号"
							className="rounded-lg"
						/>
					</Form.Item>
					<Form.Item>
						<Row gutter={8}>
							<Col span={16}>
								<Form.Item
									name="code"
									noStyle
									rules={[{ required: true, message: "请输入验证码" }]}
								>
									<Input
										prefix={
											<SafetyCertificateOutlined className="text-gray-400" />
										}
										placeholder="请输入验证码"
										className="rounded-lg"
									/>
								</Form.Item>
							</Col>
							<Col span={8}>
								<Button
									className="w-full rounded-lg"
									loading={smsLoading}
									disabled={countdown > 0}
									onClick={() => handleSendCode(form)}
								>
									{countdown > 0 ? `${countdown}秒后重试` : "获取验证码"}
								</Button>
							</Col>
						</Row>
					</Form.Item>
					<Form.Item>
						<Button
							type="primary"
							htmlType="submit"
							className="w-full rounded-lg"
							loading={loading}
						>
							{t("sys.login.loginButton")}
						</Button>
					</Form.Item>
				</Form>
			</Card>
		);
	};

	const renderContent = () => {
		switch (loginType) {
			case "register":
				return <div>Register Form</div>;
			case "forgot-password":
				return <ForgotPasswordForm onSwitch={() => setLoginType("password")} />;
			default:
				return (
					<Tabs
						activeKey={activeTab}
						onChange={setActiveTab}
						items={[
							{
								key: "password",
								label: "密码登录",
								children: <PasswordLoginForm />,
							},
							{
								key: "mobile",
								label: "验证码登录",
								children: <MobileLoginForm />,
							},
						]}
					/>
				);
		}
	};

	return <>{renderContent()}</>;
}

export default LoginForm;
